﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml.XPath;

namespace CoderJoe.Xml
{
	public static class Extensions
	{
        public static TResult GetAttributeValue<TResult>(this XElement element, string xpath, string attributeName)
        {
            return GetAttributeValue<TResult>(element, xpath, attributeName, default(TResult));
        }

        public static TResult GetAttributeValue<TResult>(this XElement element, string xpath, string attributeName, TResult defaultValue)
        {
            XElement match = element.XPathSelectElement(xpath);
            if (match != null)
            {
                XAttribute attribute = match.Attribute(attributeName);
                if (attribute != null)
                {
                    return XmlConverter.GetValue<TResult>(attribute.Value);
                }
            }

            return defaultValue;
        }

        public static TResult GetValue<TResult>(this XElement element, string xpath)
        {
            return GetValue<TResult>(element, xpath, default(TResult));
        }

        public static TResult GetValue<TResult>(this XElement element, string xpath, TResult defaultValue)
        {
            XElement match = element.XPathSelectElement(xpath);
            if (match != null)
            {
                return XmlConverter.GetValue<TResult>(match.Value);
            }

            return defaultValue;
        }
	}
}
